package com.cn.lp.export.client.base.context;

import com.google.common.base.Joiner;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Description: 请描述你的文件
 *
 * @author wuqirong
 * @date 2020-09-24
 * <p>
 * All rights Reserved, Designed www.xiao100.com
 */
public class Attributes {

    private ConcurrentHashMap<AttrKey<?>, Object> attributeMap = new ConcurrentHashMap<>();

    @SuppressWarnings("unchecked")
    public <T> T getAttribute(AttrKey<T> key) {
        return (T) this.attributeMap.get(key);
    }

    public <T> T getAttribute(AttrKey<T> key, T defaultValue) {
        T value = this.getAttribute(key);
        return value != null ? value : defaultValue;
    }


    @SuppressWarnings("unchecked")
    public <T> T removeAttribute(AttrKey<T> key) {
        return (T) this.attributeMap.remove(key);
    }


    public <T> void setAttribute(AttrKey<T> key, T value) {
        this.attributeMap.put(key, value);
    }


    @SuppressWarnings("unchecked")
    public <T> T setAttributeIfNoKey(AttrKey<T> key, T value) {
        Object oldValue = this.attributeMap.putIfAbsent(key, value);
        if (oldValue != null) {
            return (T) oldValue;
        }
        return value;
    }

    public void setAttribute(Map<AttrKey<?>, ?> map) {
        this.attributeMap.putAll(map);
    }

    public void clearAttribute() {
        this.attributeMap = new ConcurrentHashMap<>();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        sb.append(Joiner.on(",").join(attributeMap.values()));
        sb.append("]");
        return sb.toString();
    }

    public static <T> AttrKey<T> createKey(String name) {
        return () -> name;
    }

}
